package jjn.carl.backtrack;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author Jjn
 * @since 2023/7/29 14:02
 */
public class LeetCode46 {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        backtrack(nums, 0, new ArrayList<>(), result, used);
        return result;
    }
    
    private void backtrack(int[] nums, int startIndex, List<Integer> path, List<List<Integer>> result, boolean[] used) {
        if (startIndex == nums.length) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;
            }
            path.add(nums[i]);
            used[i] = true;
            backtrack(nums, startIndex + 1, path, result, used);
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int total = scanner.nextInt();
        int[] nums = new int[total];
        for (int i = 0; i < total; i++) {
            nums[i] = scanner.nextInt();
        }
        List<List<Integer>> list = new LeetCode46().permute(nums);
        System.out.println(String.join(",", list.toString()));
    }
}
